<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { useNav } from "@/layout/hooks/useNav";
import { useLayout } from "@/layout/hooks/useLayout";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { toRaw, ref, reactive } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import whQrPng from "@/assets/login/wh-qr-code.png";
import { useUserStoreHook } from "@/store/modules/user";
import type { FormInstance } from "element-plus";
import { loginRules } from "./utils/rule";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";

const loginType = ref("password");
defineOptions({
  name: "Login"
});

const router = useRouter();

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();

function changeLoginType(type) {
  loginType.value = type;
}

const ruleFormRef = ref<FormInstance>();
const loading = ref(false);
const ruleForm = reactive({
  username: "testwanhu",
  password: "a12345678"
});

const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      useUserStoreHook()
        .loginByUsername({
          username: ruleForm.username,
          password: ruleForm.password
        })
        .then(res => {
          // console.log("login res:", res);
          if (res.accessToken) {
            // 获取后端路由
            initRouter().then(() => {
              router.push("/");
              message("登录成功", { type: "success" });
            });
          } else {
            loading.value = false;
            // message(res.message, {
            //   type: "error"
            // });
            router.push("/login");
          }
        })
        .catch(err => {
          loading.value = false;
          // message(err.msg || err.message || JSON.stringify(err), {
          //   type: "error"
          // });
        });
    } else {
      loading.value = false;
      return fields;
    }
  });
};
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <!-- <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      /> -->
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>
          <div class="login-select">
            <el-row :gutter="20">
              <el-col :span="12" @click="changeLoginType('password')">
                <div
                  :class="[
                    loginType === 'password' ? 'active' : '',
                    'login-item'
                  ]"
                >
                  账号密码
                </div>
              </el-col>
              <el-col :span="12" @click="changeLoginType('qr')">
                <div
                  :class="[loginType === 'qr' ? 'active' : '', 'login-item']"
                >
                  二维码
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="login-password" v-if="loginType === 'password'">
            <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              :rules="loginRules"
              size="large"
            >
              <Motion :delay="100">
                <el-form-item
                  :rules="[
                    {
                      required: true,
                      message: '请输入账号',
                      trigger: 'blur'
                    }
                  ]"
                  prop="username"
                >
                  <el-input
                    clearable
                    v-model="ruleForm.username"
                    placeholder="账号"
                    :prefix-icon="useRenderIcon(User)"
                  />
                </el-form-item>
              </Motion>

              <Motion :delay="150">
                <el-form-item prop="password">
                  <el-input
                    clearable
                    show-password
                    v-model="ruleForm.password"
                    placeholder="密码"
                    :prefix-icon="useRenderIcon(Lock)"
                  />
                </el-form-item>
              </Motion>

              <Motion :delay="250">
                <el-button
                  class="w-full mt-4"
                  size="default"
                  type="primary"
                  :loading="loading"
                  @click="onLogin(ruleFormRef)"
                >
                  登录
                </el-button>
              </Motion>
            </el-form>
          </div>
          <div class="login-qr" v-if="loginType === 'qr'">
            <div class="qr-code">
              <img :src="whQrPng" title="中心药房分拣系统二维码" />
            </div>
            <div class="qr-tip">使用“PBM助手”小程序扫码登录</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
